package cn.wolfcode.exception;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Log;
import cn.wolfcode.service.ILogService;
import cn.wolfcode.util.RequiredPermission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component //把当前类注入到spring容器中
@Aspect    //把当前类标识为一个切面供容器读取
public class AopConfig {
    @Autowired
    private ILogService logService;

    @Autowired
    private HttpServletRequest request;
    /**
     * 指定切入点
     * 对贴有自定义注解@RequiredPermission的方法，进行切面
     */
    @Pointcut("@annotation(cn.wolfcode.util.RequiredPermission)")
    private void useMethod() {}

    /**
     * 对切入点进行增强
     */
    @Around(value = "useMethod()")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Log log = new Log();

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
        log.setOperation(annotation.name());//用户操作
        log.setReqMethod(annotation.expression());//请求方法

        Employee employee = (Employee)request.getSession().getAttribute("USER_IN_SESSION");
        log.setUser(employee.getName());//用户名
        log.setReqParam(request.getQueryString());//请求参数
        log.setIp(request.getRemoteAddr());//ip
        log.setOperTime(new Date());//操作时间

        Object result=null;

        long start = System.currentTimeMillis();

        try {
            result = proceedingJoinPoint.proceed();
            log.setOperResult(true);
        } catch (Exception e) {
            log.setError(e.getMessage());
            log.setOperResult(false);
        }finally {
            long end = System.currentTimeMillis();
            log.setRuntime(end-start);
            logService.save(log);
        }

        //执行处理方法（执行控制器中的方法）
        //result是方法的返回值，直接return回去就会返回给springmvc处理
        return result;
    }


}